package com.lg.meng.api;

import com.ihsanbal.logging.Level;
import com.ihsanbal.logging.LoggingInterceptor;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.lg.meng.BuildConfig;

import java.lang.reflect.ParameterizedType;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.internal.platform.Platform;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Author: Ligang
 * Date:  2019/9/14
 * Description:
 */
public abstract class BaseApiManager<ApiService> {
    public static final long DEFAULT_READ_TIMEOUT_MILLIS = 12 * 1000;
    public static final long DEFAULT_WRITE_TIMEOUT_MILLIS = 12 * 1000;
    public static final long DEFAULT_CONNECT_TIMEOUT_MILLIS = 12 * 1000;
    protected ApiService apiService;

    public BaseApiManager() {
        init();
    }

    protected void init() {
        Retrofit.Builder builder = new Retrofit.Builder();
        if (baseUrl() != null) {
            builder.baseUrl(baseUrl());
        }
        Converter.Factory factory = converterFactory();
        if (factory != null) {
            builder.addConverterFactory(factory);
        }
        builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create());
        builder.client(initOkHttp());
        Retrofit retrofit = builder.build();
        apiService = retrofit.create((Class<ApiService>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
    }

    protected OkHttpClient initOkHttp() {
        OkHttpClient.Builder mOkHttpClientBuilder = new OkHttpClient.Builder()
                .readTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .writeTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .connectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);

        if (BuildConfig.DEBUG) {
            //打印网络请求日志
            LoggingInterceptor httpLoggingInterceptor = new LoggingInterceptor.Builder()
                    .loggable(BuildConfig.DEBUG)
                    .setLevel(Level.BASIC)
                    .log(Platform.INFO)
                    .request("Request")
                    .response("Response")
                    .build();
            mOkHttpClientBuilder.addInterceptor(httpLoggingInterceptor);
        }
        return mOkHttpClientBuilder.build();
    }

    protected abstract String baseUrl();

    protected Converter.Factory converterFactory() {
        return GsonConverterFactory.create();
    }

}
